package com.lap.watchdog.starter.aspect;

import com.lap.framework.exception.BizException;
import com.lap.watchdog.starter.annotation.RepeatSubmit;
import com.lap.watchdog.starter.core.Repeat;
import com.lap.watchdog.starter.core.RepeatKeyGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * 防重复提交
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class RepeatSubmitAspect {

  private final Repeat repeat;

  @Around("@annotation(repeatSubmit)")
  public Object doAround(ProceedingJoinPoint pjp, RepeatSubmit repeatSubmit) throws Throwable {
    String sign = RepeatKeyGenerator.generateKey(pjp, repeatSubmit);
    log.info("防重复测试:{}", sign);
    if (repeat.isDuplicate(sign, repeatSubmit.period())) {
      throw BizException.newBiz(repeatSubmit.errorCode());
    }
    try {
      return pjp.proceed();
    } finally {
      repeat.delKey(sign);
    }
  }
}
